package com.chrisgrimble.iftu.web;

import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

public class WebServer {
    private HttpServer server;

    public WebServer(int port, WebServerMapping... mappings) {
        try {
            InetSocketAddress address = new InetSocketAddress(port);

            server = HttpServer.create(address, 0);
            for (WebServerMapping mapping : mappings) {
                server.createContext(mapping.getPath(), mapping.getResponseHandler());
            }

            server.setExecutor(Executors.newCachedThreadPool());

            server.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void stop() {
        server.stop(0);
    }    
}
